import Schema, { Rule } from "async-validator";
import React, { ChangeEvent, useContext, useEffect, useState } from "react";
import { FormContext } from "./formContext";

interface ItemProps {
  children?: React.ReactElement<{ onChange?: (value: any) => void }>;
  name?: string;
  valuePropName?: string;
  rules?: Array<Rule>;
  label?: React.ReactNode | string;
}

const Item = (props: ItemProps) => {
  const [errorInfo, setErrorInfo] = useState<string | null>(null);

  const { onValueChange, validateRegister, values } = useContext(FormContext);

  const [value, setValue] = useState<string | number | boolean>("");

  // 直接计算 propsName，每次渲染都会重新计算
  const propsName: Record<string, any> = {};
  if (props.valuePropName) {
    propsName[props.valuePropName] = value;
  } else {
    propsName.value = value;
  }

  useEffect(() => {
    if (value !== values?.[props.name!]) {
      setValue(values?.[props.name!]);
    }
  }, [values, props.name, value, props.valuePropName]);

  useEffect(() => {
    if (props.rules && props.rules.length) {
      validateRegister?.(props.name!, (formValues) => {
        console.log(formValues, "formValues");
        // 提交时使用表单传入的最新值
        return handleValidate(formValues[props.name!]);
      });
    }
  }, [props.rules, props.name]);

  const getValueFromEvent = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { target } = e;
    if (target.type === "checkbox") {
      return target.checked;
    }
    return target.value;
  };

  const handleValidate = (validateValue?: any): Promise<string> => {
    return new Promise((resolve) => {
      if (Array.isArray(props.rules) && props.rules.length) {
        const validator = new Schema({ [props.name!]: props.rules as Rule });
        // 优先使用传入的值，否则使用表单中的值
        const valueToValidate =
          validateValue !== undefined
            ? typeof validateValue === "object"
              ? validateValue[props.name!]
              : validateValue
            : values?.[props.name!];

        validator.validate({ [props.name!]: valueToValidate }, (errors) => {
          setErrorInfo(errors?.[0]?.message ?? "");
          resolve(errors?.[0]?.message ?? "");
        });
      } else {
        resolve("");
      }
    });
  };

  const elChildren =
    React.Children.toArray(props.children).length > 0
      ? React.cloneElement(props.children!, {
          ...propsName,
          onChange: (e: ChangeEvent<HTMLInputElement>) => {
            const newValue = getValueFromEvent(e);
            setValue(newValue);
            onValueChange?.(props.name!, newValue);
            handleValidate(newValue); // 直接使用新输入的值进行验证
          },
        })
      : null;

  return (
    <div>
      {props.label && <div>{props.label}</div>}
      {elChildren}
      {errorInfo && <div style={{ color: "red" }}>{errorInfo}</div>}
    </div>
  );
};

export default Item;
